package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.utils.AESUtil;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class UserRegistActivity extends BaseActivity implements View.OnClickListener{
    private String TAG="regist";
    private ImageView registback;
    private Button registcode;
    private TextView registtoup;
    private TextView registword;
    private Button registup;
    private String data;
    private String messageId;
    private EditText innumber;
    private EditText inword;
    private EditText incode;

    private String aesword;

    private String aescode;
    private String phoneno;
    private String code1;
    private String word2;
    private SharedPreferences shared;
    private SharedPreferences.Editor edit;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String longitude,latitude;
    private ImageView backmain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_regist);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "");
        longitude = sharedPreferences.getString("longitude", "");
        latitude = sharedPreferences.getString("latitude", "");
        initRegistView();

    }

    private void initRegistView() {
        registback = (ImageView) findViewById(R.id.regist_back);
        registcode = (Button) findViewById(R.id.regist_code);
        registtoup = (TextView) findViewById(R.id.regist_toup);
        registword = (TextView) findViewById(R.id.regist_word);
        registup = (Button) findViewById(R.id.registup);

        innumber = (EditText) findViewById(R.id.regist_inputphonenumber);
        inword = (EditText) findViewById(R.id.regist_inputword);
        incode = (EditText) findViewById(R.id.regist_inputcode);
        backmain = (ImageView) findViewById(R.id.userregist_backmain);

        backmain.setOnClickListener(this);

        registback.setOnClickListener(this);
        registcode.setOnClickListener(this);
        registtoup.setOnClickListener(this);
        registword.setOnClickListener(this);
        registup.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.userregist_backmain:
                startActivity(new Intent(UserRegistActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.regist_back:// 离开页面
                finish();
                break;
            case R.id.regist_toup:// 去登陆
                startActivity(new Intent(this,UserUpActivity.class));
                finish();
                break;
            case R.id.regist_code://获取验证码
                String number = String.valueOf(innumber.getText());
                if (number.equals("")){
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else {
                    MyTimer timer = new MyTimer(120000,1000);
                    timer.start();
                    getCode();
                }

                break;
            case R.id.registup:// 注册按钮
                getText();
                UserRegist();

                break;
            case R.id.regist_word://找回密码
                startActivity(new Intent(this,FindWordActivity.class));
                finish();
                break;
        }
    }
    // 获取短信验证码
    public void getCode() {

        RequestParams param1 = new RequestParams(InternetAddressUtis.Url+"/verify/sendCodeNotLogin");// 验证码接口
        param1.addHeader("Content-Type","application/json");
        param1.addHeader("appId",appId);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        getText();
        object.put("mobile",phoneno);
        object.put("type","1");
        param1.addParameter("params",object.toJSONString());
        x.http().get(param1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {


                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                // 获取appid

                data = obj.getString("data");
                com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(data);
                messageId = obj1.getString("messageId");
                shared = getSharedPreferences("messageId", Context.MODE_PRIVATE);
                edit = shared.edit();
                edit.putString("messageId",messageId);
                edit.commit();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {

            }
        });
    }
    // 用户注册
    private void UserRegist() {
       RequestParams params = new RequestParams(InternetAddressUtis.Url+"/user/userRegister");//注册接口
        // RequestParams params = new RequestParams(InternetAddressUtis.MMM);
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId",appId);
        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        getText();
        SharedPreferences ss= getSharedPreferences("messageId", Context.MODE_PRIVATE);
        String meid = ss.getString("messageId", "messageId");
        object.put("mobile",phoneno);
        object.put("password",aesword);
        object.put("latitude",latitude);
        object.put("longitude",longitude);
        object.put("messageId", meid);
        object.put("code",code1);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                // 注册成功以后 可以此处添加账号密码
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    Toast.makeText(UserRegistActivity.this, "注册成功,你可以登陆一喂了", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(UserRegistActivity.this,UserUpActivity.class));
                    finish();
                }else {
                    String failure = obj.getString("failure");
                    if (failure.equals("1001")){
                        Toast.makeText(UserRegistActivity.this, "该手机号已被注册", Toast.LENGTH_SHORT).show();
                    }else if (failure.equals("1003")){
                        Toast.makeText(UserRegistActivity.this, "账号被禁用", Toast.LENGTH_SHORT).show();

                    }else if (failure.equals("1005")){
                        Toast.makeText(UserRegistActivity.this, "短信验证码错误", Toast.LENGTH_SHORT).show();
                    }
                }

             }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "onError: 注册--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
        // 获取输入的信息
    private void  getText() {
        phoneno = String.valueOf(innumber.getText());
        word2 = String.valueOf(inword.getText());
        code1 = String.valueOf(incode.getText());

        try {
            aesword = AESUtil.encryptAES(word2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyTimer extends CountDownTimer{
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                  倒计时数        to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *           倒计时间隔               {@link #onTick(long)} callbacks.
         */
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            registcode.setClickable(false);
            registcode.setText(millisUntilFinished/1000+" s 后发送");
        }

        @Override
        public void onFinish() {
            registcode.setClickable(true);
            registcode.setText("验证码");
        }
    }
}
